package com.example.skycode7.servlet;

import com.example.skycode7.BEAN.NewsBean;
import com.example.skycode7.dao.NewsDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
@WebServlet("/newsAdd.jsp")
public class NewsAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String newstitle = req.getParameter("NewsTitle");
        String newscontent = req.getParameter("NewsContent");
        NewsBean newsBean = new NewsBean();//实例化一个新闻对象
        //设置新闻对象属性
        newsBean.setNewsTitle(newstitle);
        newsBean.setNewsContent(newscontent);
        newsBean.setNewsTime( (new Date()).toString() );
        newsBean.setAdminName("admin");
        NewsDao newsDao = new NewsDao();
        int result = newsDao.add(newsBean);
        if (result > 0) {
            //补充知识，跳转页面到news.html中
            resp.sendRedirect("newstemp.jsp");//使用结果对象 完成页面网址跳转
        }else {//失败显示错误提示页面
            req.getRequestDispatcher("WEB-INF/error.jsp").forward(req, resp);
        }
    }
}
